package com.xs.jmb2c.interceptors;

import com.xs.jmb2c.exceptions.BusinessException;
import com.xs.jmb2c.handlers.BaseContextHandler;
import com.xs.jmb2c.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        log.info("拦截器生效了......");
        String token = request.getHeader("Authorization");
        log.info("token:{}",token);

        String uri = request.getRequestURI();
        log.info("uri:{}",uri);

        if(token == null || token.equals("")){
            throw new BusinessException("token为空");
        }

        Claims claims = jwtUtil.parseToken(token);
        Long id = claims.get("id",Long.class);
        log.info("id:{}",id);
        BaseContextHandler.set(id);
        return true;
    }
}
